import { loginApi, eadyApiLogin, logoutApi } from "@/api/auth";
import { getUserInfoApi } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";

import { LoginData, EasyLoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";

export const useUserStore = defineStore("user", () => {
  const user = ref<UserInfo>({
    roles: [],
    perms: [],
  });

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((response) => {
          const { tokenType, accessToken } = response.data;
          localStorage.setItem("token", tokenType + " " + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 登录
   *
   * @param {EasyLoginData}
   * @returns
   */
  function easyLogin(loginData: EasyLoginData) {
    return new Promise<void>((resolve, reject) => {
      eadyApiLogin(loginData)
        .then((response) => {
          console.log("🚀 ~ .then ~ response:", response);
          const token = response;
          localStorage.setItem("token", token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          // const { tokenType, accessToken } = response.data;
          // localStorage.setItem("token", tokenType + " " + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      // getUserInfoApi()
      //   .then(({ data }) => {
      //     if (!data) {
      //       reject("Verification failed, please Login again.");
      //       return;
      //     }
      //     if (!data.roles || data.roles.length <= 0) {
      //       reject("getUserInfo: roles must be a non-null array!");
      //       return;
      //     }
      const data = {
        userId: 2,
        nickname: "系统管理员",
        username: "admin",
        avatar:
          "https://oss.youlai.tech/youlai-boot/2023/05/16/811270ef31f548af9cffc026dfc3777b.gif",
        roles: ["ADMIN"],
        perms: [
          "sys:menu:delete",
          "sys:dept:edit",
          "sys:dict_type:add",
          "sys:dict:edit",
          "sys:dict:delete",
          "sys:dict_type:edit",
          "sys:menu:add",
          "sys:user:add",
          "sys:role:edit",
          "sys:dept:delete",
          "sys:user:edit",
          "sys:user:delete",
          "sys:user:reset_pwd",
          "sys:dept:add",
          "sys:role:delete",
          "sys:dict_type:delete",
          "sys:menu:edit",
          "sys:dict:add",
          "sys:role:add",
        ],
      };
      Object.assign(user.value, { ...data });
      resolve(data);
      // })
      // .catch((error) => {
      //   reject(error);
      // });
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          localStorage.setItem("token", "");
          location.reload(); // 清空路由
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // remove token
  function resetToken() {
    console.log("resetToken");
    return new Promise<void>((resolve) => {
      localStorage.setItem("token", "");
      resetRouter();
      resolve();
    });
  }

  return {
    user,
    login,
    getUserInfo,
    logout,
    resetToken,
    easyLogin,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
